﻿using IdentityModel;
using IdentityServer4.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Developer.Core.IdentityServer.Api
{
    public class SysUser
    {
        /// <summary>
        /// 用户Id
        /// </summary>
        public string UserId { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName { get; set; }

        public string PassWord { get; set; }

        public string UserPhone { get; set; }
    }
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {


        private readonly IDictionary<string, SysUser> dicUser = new Dictionary<string, SysUser>()
        {
            { "User1",new SysUser(){ UserId="1", UserName="Alex",PassWord="888888",UserPhone="123123"} }
        };
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {

            if (!context.UserName.Equals(dicUser["User1"].UserName))
            {
                context.Result.ErrorDescription = $"当前用户不存在：{context.UserName}";
                await Task.CompletedTask;
                return;
            }

            if (!context.Password.Equals(dicUser["User1"].PassWord))
            {
                context.Result.ErrorDescription = $"账号密码错误";
                await Task.CompletedTask;
                return;
            }

            context.Result = new GrantValidationResult(
                        subject: dicUser["User1"].UserId.ToString(),
                        authenticationMethod: dicUser["User1"].UserName,
                        claims: GetUserClaims(dicUser["User1"]));

            await Task.CompletedTask;
        }

        // 用户身份声明
        public Claim[] GetUserClaims(SysUser user)
        {
            return new Claim[]
            {
                new Claim(JwtClaimTypes.Subject, user.UserId.ToString() ?? ""),
                new Claim(JwtClaimTypes.Id, user.UserId.ToString() ?? ""),
                new Claim(JwtClaimTypes.Name, user.UserName?? ""),
                new Claim(JwtClaimTypes.PhoneNumber, user.UserPhone  ?? "")
            };
        }
    }
}
